package cn.edu.nhic.nhcarsb.controller;

import cn.edu.nhic.nhcarsb.entity.R;
import cn.edu.nhic.nhcarsb.entity.Users;
import cn.edu.nhic.nhcarsb.service.UsersService;
import cn.edu.nhic.nhcarsb.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import freemarker.template.utility.StringUtil;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UsersService usersService;

    @GetMapping("/{uname}")
    public R checkUname(@PathVariable String uname) {
        //select count(*) from users where uname='abc'
        if (usersService.checkUname(uname)) {
            return R.error("该用户名已存在！");
        } else {
            return R.success("OK");
        }
    }

    @PostMapping
    public R register(@RequestBody Users users) {
        if (ObjectUtils.isEmpty(users.getUname())) {
            return R.error("用户名不能为空！");
        }
        if (usersService.checkUname(users.getUname())) {
            return R.error("该用户名已存在！");
        }
        return usersService.save(users) ? R.success("注册成功") : R.error("注册失败");
    }

    @PostMapping("/login")
    public R login(@RequestBody Users users, HttpSession session) {
        //select * from users where uname=? and upwd=?
        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Users::getUname, users.getUname()).eq(Users::getUpwd,
                users.getUpwd());
        Users logUsers = usersService.getOne(lambdaQueryWrapper);
        if (!ObjectUtils.isEmpty(logUsers)) {
            System.out.println(logUsers.getUid());
            String token = JwtUtils.createUserToken(logUsers.getUid());
            return R.success(token);
        } else {
            return R.error("用户名或密码错误！");
        }
    }

    @GetMapping("/session/{token}")
    public R selectSec(@PathVariable String token, HttpSession session) {
        Integer uid = JwtUtils.verifyUserTokenAndGetId(token);
        System.out.println(uid);
        return R.success(uid);
    }
}